package com.xgguo.test;


import com.xgguo.bean.User;

import java.sql.*;

/**
 * @author xgguo1
 * @date 2019/11/12 20:15
 */
public class JdbcDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/cpl?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
        String user = "root";
        String password = "123456";
        Connection conn = null;
        Statement st = null;
        ResultSet resultSet = null;

        try {
            // 1. 注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 创建一个连接对象
            conn = DriverManager.getConnection(url, user, password);
            // 3. 创建一个sql语句的发送命令对象
            String sql = "select * from tb_user;";
            st = conn.createStatement();
//             st.execute(sql);
            // 4. 执行sql语句，拿到查询的结果集对象
            resultSet = st.executeQuery(sql);
            if (resultSet.next()) {
                User user1 = new User();
                user1.setId(resultSet.getInt(1));
                user1.setName(resultSet.getString(2));
                user1.setGender(resultSet.getString(3));
                user1.getAge(resultSet.getInt(4));
                System.out.println(user1.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
